import gtk
import sys, os, shutil, stat
import time, datetime
from engine import Widgets
from lib import filesmime as mimetypes
from abcommon import *
import LocalView
from lib.libftp import *

class treeView(LocalView.treeView):
	_instance = None
	
	def __init__(self):
		LocalView.treeView.__init__(self)
		
		self.widget = self.XMLtree.getWidget("RemoteTree")
		self.ftp = Invoker(FTPConnection)
		self.__mimetype = (os.path.isfile('/usr/bin/gnome-session') \
					   and mimetypes.Gnome()) \
					   or mimetypes.notGnome(24)

	def listFiles(self, defaultPath = "", showHidden = 0):
		return self.ftp.listFiles(self.__mimetype, showHidden)
	
class treeViewEngine(treeView, LocalView.treeView):
	
	def __init__(self):
		LocalView.treeView.__init__(self)
		treeView.__init__(self)

	def pwd(self): 
		return self.ftp.pwd()
	
	def cwd(self, name): 
		self.ftp.cwd(name)
		
	#def delete(self, name): self.__FTPEngine.delete(name)
		
	#def rmdir(self, name): pass
	
class treeViewPath(LocalView.treeViewPath):
	
	def __init__(self):
		LocalView.treeViewPath.__init__(self)
		
		self.widget = self.XMLtree.getWidget("RemotePathText")
		
#class treeViewEvents(treeViewEngine, LocalView.treeViewEngine):
	
	#def __init__(self):
		#LocalView.treeViewEngine.__init__(self)
		#treeViewEngine.__init__(self)
		
class UI(treeViewEngine, LocalView.treeViewEngine, LocalView.UI):
	
	def __init__(self):
		LocalView.treeViewEngine.__init__(self)
		treeViewEngine.__init__(self)
		self.treeViewPath = treeViewPath()
		self._headerSet("header", True)
		self._columnSet("type", False, False, -1)
		self._columnSet("icon", True, False, 0)
		self._columnSet("title", True, True, 1)
		self._columnSet("size", True, True, 2)
		self._columnSet("mtime", True, True, 3)
		try: self.loadRows()
		except: pass
		self.connectEvents()
	
	def onRowClick(self, *args):
		model, iter = self.widget.get_selection().get_selected()
		file = {
			"type": model.get_value(iter, 0),
			"name": model.get_value(iter, 2)
		}
		
		if file["type"] == "directory":
			self.cwd(os.path.join(self.pwd(), file["name"]))
			self.loadRows()
			self.treeViewPath.updatePath(self.pwd())
		else:
			remotePath, hostname, username, password = \
				self.treeViewPath.get_text(), \
				self.XMLtree.getWidget("HostnameBox").get_text(), \
				self.XMLtree.getWidget("UsernameBox").get_text(), \
				self.XMLtree.getWidget("PasswordBox").get_text()
				
			down = Download(name, remotePath, hostname, username, password)
			down.run()

		LogView = Invoker(Widgets.selectWidget("LogView").UI)
		LogView.write("Remoto: %s" % self.ftp.pwd())

	def connectEvents(self):
		self.XMLtree.connectSignals({
        	"on_RemoteTree_row_clicked" : self.onRowClick,
        	"on_RemotePathText_activate": self.onPathChange,
        })